package com.aiti.lulian.gxmh.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.exception.BusinessException;
import com.aiti.base.core.utils.uuid.UUIDUtil;
import com.aiti.lulian.constant.GxmhConstant;
import com.aiti.lulian.gxmh.dto.GxmhFormDto;
import com.aiti.lulian.gxmh.dto.GxmhPolicyDeclareDto;
import com.aiti.lulian.gxmh.dto.SysUserDto;
import com.aiti.lulian.gxmh.entity.GovArticle;
import com.aiti.lulian.gxmh.entity.GxmhPolicyDeclare;
import com.aiti.base.core.base.service.iml.BaseSerivceImpl;
import com.aiti.lulian.gxmh.service.GovArticleService;
import com.aiti.lulian.gxmh.service.GxmhCustomizeFormService;
import com.aiti.lulian.gxmh.service.GxmhPolicyDeclareService;
import com.aiti.lulian.mapper.gxmh.GxmhPolicyDeclareMapper;
import com.aiti.lulian.mapper.gxmh.GxmhSysMapper;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * description:
 * auth fcb
 * date 2025-06-12 08:49
 **/
@Service
@Slf4j
public class GxmhPolicyDeclareServiceImpl extends BaseSerivceImpl<GxmhPolicyDeclareMapper, GxmhPolicyDeclare> implements GxmhPolicyDeclareService {

    @Autowired
    private GxmhSysMapper gxmhSysMapper;
    @Autowired
    private GovArticleService govArticleService;
    @Autowired
    private GxmhCustomizeFormService gxmhCustomizeFormService;

    /**
     * 首页也可以直接申报，首页申报的时候没有政策的id，因为不针对一个具体的政策申报
     * 对于首页的申报，在当前用户所属的地区创建一个特殊的政策（仅第一次时创建该政策，如果该地区存在这个特殊的政策则不再创建）
     * 然后将当前申报的数据绑定到这个特殊的政策上
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized void savePolicyDeclare(GxmhPolicyDeclareDto dto) {
        this.checkParams(dto);
        // 企业是否认证
        Integer count = this.baseMapper.queryCountByEnterpriseId(dto.getEnterpriseId());
        if (count == 0) {
            throw new BusinessException("当前企业还未认证，暂无法申报");
        }
        if(StrUtil.isEmpty(dto.getPolicyId())) {
            // 查询特殊的政策是否存在
            String specialPolicyId = this.baseMapper.querySpecialPolicyId(dto.getProvince(), dto.getCity(), dto.getCounty(), dto.getStreet());
            if(StrUtil.isEmpty(specialPolicyId)) {
                String policyId = UUIDUtil.getUUID();
                GovArticle specialPolicy = new GovArticle();
                specialPolicy.setBaseId(policyId);
                // 综合政策
                specialPolicy.setPolicyType("bd20c662de6611ec848100163e06b123");
                specialPolicy.setTitle("政策匹配");
                specialPolicy.setProvince(dto.getProvince());
                specialPolicy.setCity(dto.getCity());
                specialPolicy.setCounty(dto.getCounty());
                specialPolicy.setStreet(dto.getStreet());
                specialPolicy.setBody("该政策由系统创建，请勿修改删除");
                specialPolicy.setSource("系统");
                specialPolicy.setArticleType("match");
                specialPolicy.setArticlePublishTime(new Date());
                specialPolicy.setIsDelete(0);
                specialPolicy.setBaseCreateTime(new Date());
                specialPolicy.setFormId(GxmhConstant.DEFAULT_FORM_ID);
                govArticleService.save(specialPolicy);

                dto.setPolicyId(policyId);
            }else {
                dto.setPolicyId(specialPolicyId);
            }
        }
        // 申报是否重复
        Integer enterprisePolicyCount = this.baseMapper.queryCountByEnterpriseIdAndPolicyId(dto.getEnterpriseId(), dto.getPolicyId());
        if (enterprisePolicyCount > 0) {
            throw new BusinessException("当前企业已经申报过该政策");
        }
        // 判断是否是自定义表单，如果是自定义的表单则只保存json数据
        if(StrUtil.isNotBlank(dto.getFormId()) && !GxmhConstant.DEFAULT_FORM_ID.equals(dto.getFormId())) {
            GxmhPolicyDeclare po = new GxmhPolicyDeclare();
            po.setBaseId(UUIDUtil.getUUID());
            po.setEnterpriseId(dto.getEnterpriseId());
            po.setPolicyId(dto.getPolicyId());
            po.setCustomFormDataJson(JSON.toJSONString(dto.getFormData()));
            po.setBaseCreateBy(dto.getEnterpriseId());
            po.setBaseCreateTime(DateUtil.date());
            po.setIsDelete(0);
            po.setBaseUpdateBy(dto.getEnterpriseId());
            po.setBaseUpdateTime(DateUtil.date());
            this.save(po);
            return;
        }
        GxmhPolicyDeclare po = new GxmhPolicyDeclare();
        po.setBaseId(UUIDUtil.getUUID());
        po.setEnterpriseId(dto.getEnterpriseId());
        po.setPolicyId(dto.getPolicyId());
        po.setEnterpriseName(dto.getEnterpriseName());
        po.setRegisterFund(dto.getRegisterFund());
        po.setEnterpriseCreateTime(DateUtil.parse(dto.getEnterpriseCreateTime()));
        po.setArea(dto.getArea());
        po.setIndustry(dto.getIndustry());
        po.setIndustryScale(dto.getIndustryScale());
        po.setMainIncome(dto.getMainIncome());
        po.setBaseCreateBy(dto.getEnterpriseId());
        po.setBaseCreateTime(DateUtil.date());
        po.setIsDelete(0);
        po.setBaseUpdateBy(dto.getEnterpriseId());
        po.setBaseUpdateTime(DateUtil.date());
        po.setProvince(dto.getProvince());
        po.setCity(dto.getCity());
        po.setCounty(dto.getCounty());
        po.setStreet(dto.getStreet());
        po.setFirstIndustryId(dto.getFirstIndustryId());
        po.setSecondIndustryId(dto.getSecondIndustryId());
        po.setPhone(dto.getPhone());
        this.save(po);
    }

    /**
     * 获取该政策的表单信息
     * @param policyId
     * @return
     */
    public GxmhFormDto getFromDetail(String policyId) {
        if(StrUtil.isBlank(policyId)) {
            throw new BusinessException("参数错误");
        }
        String formId = this.baseMapper.queryFormIdByPolicyId(policyId);

        return gxmhCustomizeFormService.getFromDetail(formId);
    }

    private void checkParams(GxmhPolicyDeclareDto dto) {
        if(StrUtil.isBlank(dto.getEnterpriseId())) {
            throw new BusinessException("参数错误，企业id不能为空");
        }
//        if(StrUtil.isBlank(dto.getPhone())) {
//            throw new BusinessException("参数错误，联系电话不能为空");
//        }
        // 首页直接申报的时候没有政策的id
//        if(StrUtil.isBlank(dto.getPolicyId())) {
//            throw new BusinessException("参数错误，政策id不能为空");
//        }
    }

}
